package com.honeywell.iotserver.rabbitmq;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.honeywell.iotserver.utils.MyProps;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

@Component
public class MessageSender {
	
	private Logger logger = LoggerFactory.getLogger(MessageSender.class);

	@Autowired
	private MyProps myProps;
	public boolean sendOnOffAlarmMessage(String message) {
		try {

			ConnectionFactory factory = new ConnectionFactory();
			factory.setHost(myProps.getRabbitmq_host());
	        factory.setUsername(myProps.getRabbitmq_username());
	        factory.setPassword(myProps.getRabbitmq_password());
	        factory.setPort(myProps.getRabbitmq_port());
			Connection connection = factory.newConnection();
			Channel channel = connection.createChannel();
			channel.basicPublish(myProps.getExchange_on_off_alarm(), myProps.getRouting_key_on_off_alarm(), null, message.getBytes());
			logger.info("Sent MESSAGE'" + message + "'");
			channel.close();
			connection.close();
		} catch (IOException | TimeoutException e) {
			logger.error("send message faild!", e);
			return false;
		}
		
		return true;
	}
}